/**
 * Module dependencies.
 */
const Koa = require('koa');
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser');
const logger = require('koa-logger');
const conditional = require('koa-conditional-get');
const etag = require('koa-etag');
const compress = require('koa-compress');
const serve = require('koa-static');
const responseTime = require('koa-response-time');
const cors = require('kcors');
const historyApiFallback = require('koa2-history-api-fallback');
const passport = require('koa-passport');
const session = require("koa-session2");
const authMiddleware = require('./middleware/authMiddleware');

/**
 * import routers
 */
const router = require('./router/routes').route;

/**
 * 初始化数据库
 */
require('./platform/');

/**
 * 創建Koa实例
 */
const app = new Koa();

/**
 * Environment
 */
const env = process.env.NODE_ENV || 'development';
const COOKIE_EXPIRED = 1000 * 3600 * 24 * 30;

/**
 * error handler
 */
onerror(app)

/**
 * keys
 */
app.keys = ['personal-learning-api'];

/**
 * middlewares
 */

// etag works together with conditional-get
app.use(conditional());
app.use(etag());

// 允许跨域
app.use(cors({
  credentials: true,
}));

// gzip 压缩
app.use(compress());

//解析post数据
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}));

// json解析
app.use(json());

// x-response-time
app.use(responseTime());

// logger
if ('test' != env) app.use(logger());

// static server
app.use(serve(__dirname + '/public'));

// logger
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

//history-api-fallback
// app.use(historyApiFallback());

// session
app.proxy = true;
app.use(session({ key: 'learning.sid' }));


// passport
require('./auth/passport_config');
app.use(passport.initialize());
app.use(passport.session());

// //auth
app.use(authMiddleware);


//路由
app.use(router().routes());



/**
 * error-handling
 */
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx);
});


module.exports = app;